/**
 * Created by zhouli on 18/9/8
 * Email li.zhou@huilianyi.com
 */
//自定义值列表项详情
import React from 'react';
import {connect} from 'react-redux';
import {Table,Input, message, Icon, Tabs, Badge} from 'antd';
import CVIDService from 'containers/setting/value-list/custom-value-item-detail/custom-value-item-detail.service';
import menuRoute from 'routes/menuRoute';
import BasicInfo from 'components/basic-info';
import 'styles/setting/value-list/custom-value-item-detail/custom-value-item-detail.scss';
import {messages} from 'share/common';
import {SelectDepOrPerson} from 'components/index';
const TabPane = Tabs.TabPane;
import ResizeTable from "components/resize-table";

class CustomValueItemDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      nowStatus: 'PERSONADD',//当前的tab
      data: [],
      dataDep: [],//管联的部门数据
      customValueItemUserName: "",//输入搜索自定义值列表项人员名称与工号
      customValueItemDepName: "",//输入搜索自定义值列表项 部门名称与编码
      //tabs标题
      tabs: [
        {key: 'PERSONADD', name: messages('setting.key314'/*按人员添加*/)}, /*按人员添加*/
        {key: 'DEPARTMENT', name: messages('setting.key1212'/*按部门添加(含子部门)*/)}, /*按部门添加(含子部门)*/
      ],
      columns: [
        {
          title: messages('common.user.id')/*工号*/,
          dataIndex: "employeeID",
          width: '15%'
        },
        {
          title: messages('setting.key1213'/*姓名*/),
          dataIndex: "fullName",
          width: '15%'
        },
        {
          title: messages('common.department')/*部门*/,
          dataIndex: "departmentName",
          width: '25%'
        },
        {
          title: messages('setting.key1214'/*职位*/),
          dataIndex: "title",
          width: '15%'
        },
      ],
      columnsDep: [
        {
          title: messages('setting.key1215'/*部门编码*/),
          dataIndex: "departmentCode",
          width: '15%'
        },
        {
          title: messages('setting.key1216'/*部门名称*/),
          dataIndex: "departmentName",
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: "enabled",
          width: '25%',
          render: isEnabled => (
            <Badge status={isEnabled ? 'success' : 'error'}
                   text={isEnabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },

      ],//关联的部门表格
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      //这里先确定固定的字段
      infoList: [
        {
          type: 'input',
          label: messages('setting.key1217'/*值名称*/),
          id: 'messageKey',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key1218'/*编码*/),
          id: 'code',
          disabled: true
        },
        {
          type: 'input',
          label: messages('common.sequence')/*序号*/,
          id: 'sequenceNumber',
          disabled: true
        },
        {
          type: 'input',
          label: messages('common.remark')/*备注*/,
          id: 'remark',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('common.column.status')/*状态*/,
          id: 'enabled',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('setting.key1219'/*全员可见*/),
          id: 'common',
          disabled: true
        },
      ],
      infoData: {},
      valueListDetail: menuRoute.getRouteItem('value-list-detail', 'key'),//值列表详情
    };
  }

  componentWillMount() {
    let columns = this.state.columns;
    let columnsDep = this.state.columnsDep;
    if (this.props.tenantMode) {
      let operation = {
        title: messages("common.operation"),//"操作",
        dataIndex: "id",
        render: (text, record) => (
          <span>
            <a onClick={(e) => this.delPersonValueListItem(e, record)}>
              {messages("common.delete")}
            </a>
          </span>
        )
      }
      let operationDep = {
        title: messages("common.operation"),//"操作",
        dataIndex: "id",
        render: (text, record) => (
          <span>
            <a onClick={(e) => this.delDepValueListItem(e, record)}>
              {messages("common.delete")}
            </a>
          </span>
        )
      }
      columns.push(operation);
      columnsDep.push(operationDep);
    }
  }

  componentDidMount() {
    this.getDetailValueListItem();
  }

  getDetailValueListItem() {
    CVIDService.getDetailValueListItem(this.props.params.customValueItemOID)
      .then(res => {
        let data = res.data;
        this.setState({
          infoData: data
        }, () => {
          this.getList();
        })
      })
  }

  //根据key获取对应的列表
  getList = () => {
    let key = this.state.nowStatus;
    if (key === "PERSONADD") {
      this.getUserList();
    } else if (key === "DEPARTMENT") {
      this.getDepartmentList();
    }
  };
  //获取管理的部门列表
  getDepartmentList = () => {
    this.setState({loading: true});
    let pagination = this.state.pagination;
    let infoData = this.state.infoData;
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
      customEnumerationItemOID: infoData.customEnumerationItemOID,
      keyword: this.state.customValueItemDepName,
    }
    CVIDService.getDepValueListItem(params, infoData.id)
      .then((response) => {
        response.data.map((item) => {
          item.key = item.id;
        });
        pagination.total = Number(response.headers['x-total-count']);
        pagination.current = params.page + 1;
        this.setState({
          dataDep: response.data,
          loading: false,
          pagination
        })
      });
  }

  //得到列表数据
  getUserList() {
    this.setState({loading: true});
    let pagination = this.state.pagination;
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
      customEnumerationItemOID: this.state.infoData.customEnumerationItemOID,
      keyword: this.state.customValueItemUserName,
    }
    CVIDService.getPersonValueListItem(params)
      .then((response) => {
        response.data.map((item) => {
          item.key = item.id;
        });
        pagination.total = Number(response.headers['x-total-count']);
        pagination.current = params.page + 1;
        this.setState({
          data: response.data,
          loading: false,
          pagination
        })
      });
  }

  // -----非编辑状态---end
  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getList();
    })
  };

  //批量添加人员
  addPersonOrDepValueListItem = (res) => {
    if (res.depList.length < 1 && res.personList.length < 1) {
      message.warn(messages('setting.key1220'/*请选择人员*/));
      return;
    }
    let userOIDs = [];
    let depOIDS = res.depList;
    res.personList.map((item) => {
      userOIDs.push(item.userOID);
    })

    let params = {
      userOIDs: userOIDs,
      departmentDTOs: depOIDS,
      customEnumerationItemOID: this.props.params.customValueItemOID,
      customEnumerationOID: this.props.params.customEnumerationOID,
    }
    CVIDService.addPersonOrDepValueListItem(params)
      .then((res) => {
        message.success(messages('common.operate.success')/*操作成功*/)
        this.getUserList();
        this.getDepartmentList();
      })
  }


  //删除人
  delPersonValueListItem = (e, record) => {
    let params = {
      "userOIDs": [record.userOID],
      "customEnumerationItemOID": this.props.params.customValueItemOID,
    }
    CVIDService.delPersonValueListItem(params)
      .then(res => {
        this.getUserList();
        message.success(messages('common.operate.success')/*操作成功*/)
      })
  }

  //删除部门
  delDepValueListItem = (e, record) => {
    CVIDService.delDepValueListItem(record.id)
      .then(res => {
        this.getDepartmentList();
        message.success(messages('common.operate.success')/*操作成功*/)
      })
  }

  //返回值列表
  backToValueListDetail = () => {
    let path = this.state.valueListDetail.url.replace(':customEnumerationOID', this.props.params.customEnumerationOID);
    let _path = path.replace(':customEnumerationID', this.props.params.customEnumerationID);
    this.context.router.push(_path);
  }
  //搜索自定义值列表项的人
  emitEmptyForUser = () => {
    this.userNameInput.focus();
    this.setState({customValueItemUserName: ''}, () => {
      this.onChangeCustomValueItemUserName();
    });
  }
  //搜索自定义值列表项的部门
  emitEmptyForDep = () => {
    this.DepNameInput.focus();
    this.setState({customValueItemDepName: ''}, () => {
      this.onChangeCustomValueItemDepName();
    });
  }
  //搜索自定义值列表项的人
  onChangeCustomValueItemUserName = (e) => {
    let customValueItemUserName = "";
    if (e) {
      customValueItemUserName = e.target.value;
    }
    this.setState({
      customValueItemUserName: customValueItemUserName,
      loading: true
    }, () => {
      //搜索
      this.getUserList();
    });
  }

  //搜索自定义值列表项的部门
  onChangeCustomValueItemDepName = (e) => {
    let customValueItemDepName = "";
    if (e) {
      customValueItemDepName = e.target.value;
    }
    this.setState({
      customValueItemDepName: customValueItemDepName,
      loading: true
    }, () => {
      //搜索
      this.getDepartmentList();
    });
  }

  //渲染部门或者人员选择组件
  renderDepComponents = () => {
    const {tenantMode, company} = this.props;
    return <div>
      <SelectDepOrPerson
        depCompany={!tenantMode ?{
          companyName:company.name,
          companyId:company.id,
          companyOID:company.companyOID
        }:{}}
        buttonType={"primary"}
        depResList={["id", "departmentOID","departmentCode","parentDepartmentOID","parentDepartmentId","custDeptNumber"]}
        personResList={["id", "userOID"]}
        title={messages('setting.key1221'/*批量添加员工或部门*/)}
        onConfirm={this.addPersonOrDepValueListItem}/>
    </div>
  }
  //渲染Tabs
  renderTabs = () => {
    const {columns, columnsDep, dataDep, data, loading, pagination, tabs} = this.state;
    const suffix = this.state.customValueItemUserName ? <Icon type="close-circle"
                                                              onClick={this.emitEmptyForUser}/> : null;
    const suffixDep = this.state.customValueItemDepName ? <Icon type="close-circle"
                                                                onClick={this.emitEmptyForDep}/> : null;
    return (
      tabs.map(tab => {
        if (tab.key === 'PERSONADD') {
          return <TabPane tab={tab.name} key={tab.key}>
            <div>
              <div className="table-header">
                <div className="table-header-buttons">
                  <div className="f-left total-title">
                    {messages("common.total", {total: pagination.total})}
                  </div>
                  <div className="table-header-inp f-right">
                    <Input
                      className='item-user-name-search'
                      key={'customValueItemUserName-search'}
                      placeholder={messages('setting.key1222'/*输入姓名/工号*/)}
                      prefix={<Icon type="search" className='font-disabled'/>}
                      suffix={suffix}
                      value={this.state.customValueItemUserName}
                      onChange={this.onChangeCustomValueItemUserName}
                      ref={node => this.userNameInput = node}
                    />
                  </div>
                  <div className="clear"/>

                </div>
              </div>
              <ResizeTable
                columns={columns}
                dataSource={data}
                pagination={pagination}
                loading={loading}
                onChange={this.onChangePager}
                rowKey="userOID"
                bordered
                size="middle"
              />
            </div>

          </TabPane>
        } else if (tab.key === 'DEPARTMENT') {
          return <TabPane tab={tab.name} key={tab.key}>
            <div>
              <div className="table-header">
                <div className="table-header-buttons">
                  <div className="f-left total-title">
                    {messages("common.total", {total: pagination.total})}
                  </div>
                  <div className="table-header-inp f-right">
                    <Input
                      className='center-item-user-name-search'
                      key={'customValueItemDepName-search'}
                      placeholder={messages('setting.key1223'/*输入部门名称/编码*/)}
                      prefix={<Icon type="search" className='font-disabled'/>}
                      suffix={suffixDep}
                      value={this.state.customValueItemDepName}
                      onChange={this.onChangeCustomValueItemDepName}
                      ref={node => this.DepNameInput = node}
                    />
                  </div>
                  <div className="clear"/>

                </div>
              </div>
              <ResizeTable
                columns={columnsDep}
                dataSource={dataDep}
                pagination={pagination}
                loading={loading}
                onChange={this.onChangePager}
                rowKey="id"
                bordered
                size="middle"
              />
            </div>
          </TabPane>
        }
      })
    )
  }
  //点击
  onChangeTabs = (key) => {
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.total = 0;
    this.setState({
      nowStatus: key,
      loading: true,
      pagination,
    }, () => {
      this.getList();
    })
  };
  render() {
    const {infoList, infoData} = this.state;
    return (
      <div className="custom-value-item-detail">
        <BasicInfo infoList={infoList}
                   infoData={infoData}
                   isHideEditBtn={true}
        />
        <p/>
        {infoData.common ? <div/> : this.renderDepComponents()}
        {infoData.common ? <div/> : <Tabs onChange={this.onChangeTabs} style={{marginTop: 20}}>
          {this.renderTabs()}
        </Tabs>}

        <a className="back" onClick={this.backToValueListDetail}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>
          {messages('common.back')}
        </a>
      </div>
    )
  }
}

CustomValueItemDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CustomValueItemDetail);
